package com.mall.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.pageResult.PageResult;
import com.mall.pojo.PmsProductAttributeCategory;
import com.mall.service.PmsProductAttributeCategoryService;
import com.mall.utils.Result;
import com.mall.vo.PpacVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("productAttribute")
public class PmsProductAttributeCategoryController {

    @Autowired
    private PmsProductAttributeCategoryService pmsProductAttributeCategoryService;

    //添加商品属性分类
    @PostMapping("/category/create")
    public Result create(@RequestParam("name") String name) {
        pmsProductAttributeCategoryService.create(name);
        return Result.success(null, "");
    }

    //删除单个商品属性分类
    @GetMapping("/category/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        pmsProductAttributeCategoryService.delete(id);
        return Result.success(null, "");
    }

    //分页获取所有商品属性分类
    @GetMapping("/category/list")
    public Result<PageResult<PmsProductAttributeCategory>> list(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        PageResult<PmsProductAttributeCategory> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        Page<PmsProductAttributeCategory> page = pmsProductAttributeCategoryService.list(pageNum, pageSize);
        if (CollUtil.isEmpty(page.getRecords())) {
            pageResult.setList(new ArrayList<>());
            return Result.success(pageResult,"操作成功");
        }
        pageResult.setList(page.getRecords());
        pageResult.setTotal(Convert.toInt(page.getTotal()));
        pageResult.setTotalPage(Convert.toInt(page.getPages()));
        return  Result.success(pageResult,"操作成功");
    }

    //获取所有商品属性分类及其下属性
    @GetMapping("/category/list/withAttr")
    //vo里是两张表
    public Result<List<PpacVo>> withAttr(){
        List<PpacVo> list = pmsProductAttributeCategoryService.withAttr();
        return Result.success(list, "");
    }

    //修改商品属性分类
    @PostMapping("/category/update/{id}")
    public Result update(@PathVariable("id") Integer id, @RequestParam("name") String name) {
        pmsProductAttributeCategoryService.update(id, name);
        return Result.success(null, "");
    }

    //获取单个商品属性分类信息
    @GetMapping("/category/{id}")
    public Result<PmsProductAttributeCategory> selectById(@PathVariable("id") Integer id){
        PmsProductAttributeCategory ppac = pmsProductAttributeCategoryService.selectById(id);
        return Result.success(ppac,"");
    }

}


